﻿/*!
 * js类，支持继承，多态，目前用在房源新增，编辑
 * 用例
 * var a = new Class({a:1,b:2});
 * var b = new Class({c:1},a);
 * @parent 父类
 * 作者：赵贲
 */
var Class = function (object, parent) {
    var klass = function () {
        //执行父类的构造函数
        var inits = [];
        var temfn = this;
        while (temfn.base) {
            inits.push(temfn.base.init);
            temfn = temfn.base;
        }
        for (var i = inits.length - 1; i >= 0; i--) {
            inits[i].apply(this, arguments);
        }
        this.init.apply(this, arguments);
    };
    // 改变klass 的原型  
    if (parent) {
        var subclass = function () { };
        subclass.prototype = parent.prototype;
        klass.prototype = new subclass;
        klass.prototype.base = new subclass;
    };
    if (!klass.prototype.init) {
        klass.prototype.init = function () { };
    }
    // 定义别名  
    klass.fn = klass.prototype;
    // 添加一个proxy 函数  
    klass.proxy = function (func) {
        var self = this;
        return (function () {
            return func.apply(self, arguments);
        });
    }
    // 在实例中也添加这个函数  
    klass.fn.proxy = klass.proxy;
    klass.fn.parent = klass;
    klass._super = klass.__proto__;
    // 给类添加属性  
    klass.extend = function (obj) {
        var extended = obj.extended;
        for (var i in obj) {
            klass[i] = obj[i];
        }
        if (extended) extended(klass);
    };
    // 给实例添加属性  
    klass.include = function (obj) {
        var included = obj.included;
        for (var i in obj) {
            klass.fn[i] = obj[i];
        }
        if (included) included(klass);
    };
    //自已加的
    if (object) {
        klass.include(object);
    }
    return klass;
};

String.prototype.format = function () {
    var args = arguments;
    return this.replace(/\{(\d+)\}/g,
        function (m, i) {
            return args[i];
        });
}
String.format = function () {
    if (arguments.length == 0)
        return null;

    var str = arguments[0];
    for (var i = 1; i < arguments.length; i++) {
        var re = new RegExp('\\{' + (i - 1) + '\\}', 'gm');
        str = str.replace(re, arguments[i]);
    }
    return str;
}
